#!/user/bin/env node

const log = console.log,
      http = require('http'),
      url = require('url'),
      qs = require('querystring');
let page = process.argv[2];
page = `item=${page}`;

let items = [];

http.createServer((req,res)=>{
  let path = url.parse(req.url).pathname;

  if(path !== '/'){
    //if(req.url===`item=${item[0]}`){
      //log('jion')
      //res.end(`welcome to ${page}`);
   // }
    err(res);
    log('not found page');
    return;
  }
  log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
  log('url:',req.url);
  log('header:',req.headers);

  add(req,res);
  log('after add',items);
  //if(req.url === `item=${items[0]}`){
    //log('3',items);
    //res.end('welcome to newpage');
  //}
}).listen(8080);

function add(req,res){
  let value = qs.parse(url.parse(req.url).query).item;
  if(typeof value !== 'undefined' && value !== ''){
    items.push(value);
  }
  log(items);
  show(res);
}

function show(res){
  const html = `
    <!DOCTYPE html>
      <html>
        <head>
        <meta charset="UTF-8">
          <title>Todo list</title>
          </head>
        <body>
          <h1>Todo List</h1>
          <form method="get" action="/">
          <p><input type="text" name="item" />
          <input type="submit" value="Add Item" /></p>
          </form>
          <ul>
            ${items.map(item => '<li>' + item + '</li>').join('\n')}
          </ul>
        </body>
      </html>`;

    res.setHeader('Content-Type','text/html');
    res.setHeader('content-Length',Buffer.byteLength(html));

      res.statusCode = 200;
      res.end(html);
}

function err(res){
  let msg = 'not found!';
  res.statusCode = 404;
  res.setHeader('Content-Length',msg.length);
  res.setHeader('Content-Type','text/plain');
  res.end(msg);
}
